package cn.wbnyua.resume.core.exception;

import cn.wbnyua.resume.util.JsonResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;

/**
 * 作者：wbnyua.
 * 创建时间: 2023/2/6 21:33.
 */

@ControllerAdvice
@Order(Ordered.HIGHEST_PRECEDENCE)
public class GlobalExceptionAdvice {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    @ResponseStatus(code = HttpStatus.BAD_REQUEST)
    public JsonResponse<String> exceptionHandler(HttpServletRequest request, Exception e){
        String errorMsg = e.getMessage();
        if (e instanceof RuntimeExceptionHandler){
            String errorCode = ((RuntimeExceptionHandler)e).getCode();
            return new JsonResponse<>(errorCode,errorMsg);
        }else {
            return new JsonResponse<>("500",errorMsg);
        }
    }

}
